package com.szgr.baoyin.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.DialogUtils;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends BaseActivity {

    private static final int LOGIN_GO = 99;
    private static final int REGISTER_BACK = 100;
    private EditText et_username;
    private EditText et_password;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constant.REQUEST_SUCCESS:
                    DialogUtils.hideLoadingDialog();
                    String key = (String) msg.obj;
                    MyApplication.getmInstance().setUsername(et_username.getText().toString().trim());
                    MyApplication.getmInstance().setUserPhone(et_username.getText().toString().trim());
                    MyApplication.getmInstance().setPassword(et_password.getText().toString().trim());
                    MyApplication.getmInstance().setKey(key);
                    MyApplication.getmInstance().setIsLogin(true);
                    MyTool.saveSP("username", et_username.getText().toString().trim());
                    MyTool.saveSP("password", et_password.getText().toString().trim());
                    finish();
                    break;
                case 1008:
                    DialogUtils.hideLoadingDialog();
                    ToastUtils.showToast("登陆失败，请检查网络后重试！");
                    break;
                case 1009:
                    DialogUtils.hideLoadingDialog();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login2);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("登录");
    }

    @Override
    public void initView() {
        findViewById(R.id.login_to_register).setOnClickListener(this);
        findViewById(R.id.login_to_find).setOnClickListener(this);
        findViewById(R.id.login_btn).setOnClickListener(this);

        et_username = (EditText) findViewById(R.id.login_username);
        et_password = (EditText) findViewById(R.id.login_password);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.login_to_register:
                startActivityForResult(new Intent(this,RegisterActivity.class),LOGIN_GO);
                break;
            case R.id.login_to_find:
                Intent passIntent = new Intent(this,RegisterActivity.class);
                passIntent.putExtra("from","edit");
                startActivity(passIntent);
                break;
            case R.id.login_btn:
                if(MyTool.isEmpty(et_username)){
                    ToastUtils.showToast("登录名不能为空");
                    return;
                }
                if(MyTool.isEmpty(et_password)){
                    ToastUtils.showToast("登录密码不能为空");
                    return;
                }
                doLogin();
                break;
        }
    }

    private void doLogin() {
        DialogUtils.showLoadingDialog(this,"正在登录...");
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_LOGIN,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.getString("code");
                            if("200".equals(code)) {
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                if (datas.has("error") || datas.has("errorcode")) {
                                    ToastUtils.showToast(datas.getString("error"));
                                    mHandler.sendEmptyMessage(1009);
                                } else {
                                    String key = datas.getString("key");
                                    mHandler.obtainMessage(Constant.REQUEST_SUCCESS,key).sendToTarget();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            mHandler.sendEmptyMessage(1008);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mHandler.sendEmptyMessage(1008);
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("username",et_username.getText().toString().trim());
                map.put("password",et_password.getText().toString().trim());
                map.put("client","android");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(data != null && resultCode == REGISTER_BACK){
            Bundle extras = data.getBundleExtra("bundle");
            String username = extras.getString("username");
            String password = extras.getString("password");
            et_username.setText(username);
            et_password.setText(password);
        }
    }
}
